// 文章相关 action

import { ArticleDetailResponse } from '@/types/data';
import { RootThunkAction } from '@/types/store';
import { http } from '@/utils/http';
// // 导入dayjs
// import dayjs from 'dayjs';
// // 导入本地化格式插件
// import localizedFormat from 'dayjs/plugin/localizedFormat';
// dayjs.extend(localizedFormat);

// 获取文章详情
export const getArticleById = (id: string): RootThunkAction => {
  return async (dispatch) => {
    // 获取文章详情
    const res = await http.get<ArticleDetailResponse>(`/articles/${id}`);
    console.log('文章详情res', res.data.data);

    // 把文章详情交给reducer
    dispatch({
      type: 'article/getArticleById',
      // payload: {
      //   ...res.data.data,
      //   pubdate: dayjs(res.data.data.pubdate).locale('zh-cn').format('LL'),
      // },
      payload: res.data.data,
    });
  };
};

// 关注或取消关注
export const followAuthor = (
  id: string,
  isFollowed: boolean
): RootThunkAction => {
  return async (dispatch) => {
    if (isFollowed) {
      // 取消关注
      const res = await http.delete(`/user/followings/${id}`);
      console.log('取消关注res', res);
    } else {
      // 关注
      console.log('关注id', id);
      const res = await http.post('/user/followings', { target: id });
      console.log('关注res', res);
    }

    // 更新redux中的文章详情数据，这里没有必要额外发起请求
    dispatch({
      type: 'article/updateInfo',
      payload: { name: 'is_followed', value: !isFollowed },
    });
  };
};
